import {Injectable} from '@nestjs/common';
// ORM
import {InjectRepository} from '@nestjs/typeorm';
import {Repository, UpdateResult} from 'typeorm';
import {OperateLogDto} from '../dto/operate.log.dto';
import {OperateLogEntity} from "../entity/operate.log.entity";
import {UserListEntity} from "../entity/user.list.entity";

@Injectable()
export class OperateLogService {
    constructor(
        @InjectRepository(OperateLogEntity)
        private readonly operateLogRepository: Repository<OperateLogEntity>,
    ) {
    }

    async createOne(operateLogDto: OperateLogDto): Promise<OperateLogEntity> {
        return await this.operateLogRepository.save(operateLogDto);
    }

    async getListByPaginationAndCondition(pageIndex: number, pageSize: number, toUserId: string, type: string): Promise<[OperateLogEntity[], number]> {
        const qb = this.operateLogRepository.createQueryBuilder('operate')
        if (toUserId) {
            qb.where({toUserId})
        }
        if (type) {
            qb.andWhere({type})
        }
        qb.leftJoinAndMapOne('operate.toUserInfo', UserListEntity, 'user', 'operate.toUserId = user.userId')
        qb.orderBy({
            'operate.time': 'DESC'
        })
        qb.offset((pageIndex - 1) * pageSize).limit(pageSize)
        return qb.getManyAndCount()
    }
}
